package com.tianpengtech.front.mobile.bankno;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianpengtech.common.model.fairbankno.FairBankno;
import com.tianpengtech.front.mobile.common.util.R;

import java.util.List;
import java.util.Map;

/**
 * Created by ggd on 2017/7/26 0026.
 */
public class MobileBanknoService {
    public static MobileBanknoService me = new MobileBanknoService();
    private static FairBankno dao = FairBankno.dao;

    /**
     * 保存银行卡信息
     * @param param
     * @return
     */
    public R save(Map<String,String> param) throws Exception{
        try{
            String wh_id=param.get("id");
            String bank=param.get("bank");
            String bank_no=param.get("bank_no");
            String real_name=param.get("real_name");
            if (isBankNoExists(bank_no,Long.parseLong(wh_id))){
                return R.fail("此银行卡已添加过");
            }
            FairBankno fb = new FairBankno();
            fb.set(FairBankno.WH_ID,wh_id);
            fb.set(FairBankno.BANK,bank);
            fb.set(FairBankno.BANK_NO,bank_no);
            fb.set(FairBankno.REAL_NAME,real_name);
            fb.save();
            R r=R.ok("成功");
            r.p("bankno",fb);
            CacheKit.remove(FairBankno.CACHE_NAME,"bankno_"+wh_id);
            return r;
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

    /**
     *  获取某个人得银行卡列表
     * @param id
     * @return
     */
    public R findBankno(long id){
        String sql = String.format("select %s,%s,%s from %s where %s=? and %s=?",FairBankno.ID,FairBankno.BANK,FairBankno.BANK_NO,dao.tableName(),FairBankno.DELETETAG,FairBankno.WH_ID);
        List<FairBankno> list=dao.findByCache(FairBankno.CACHE_NAME,"bankno_"+id,sql,0,id);
        R r = R.ok();
        r.p("banknos",list);
        return r;
    }

    /**
     * 判断用的银行卡是否添加过
     * @param bankNo
     * @param uid
     * @return
     */
    public boolean isBankNoExists(String bankNo,long uid){
        String sql = String.format("select %s from %s where %s=? and %s=? and %s=?",FairBankno.ID,dao.tableName(),FairBankno.DELETETAG,FairBankno.WH_ID,FairBankno.BANK_NO);
        FairBankno no=dao.findFirst(sql,0,uid,bankNo);
        if (no==null){
            return false;
        }else{
            return true;
        }
    }


    /**
     * 判断用的银行卡是否添加过
     * @return
     */
    public boolean isBankNoExists(String bankId){
        String sql = String.format("select %s from %s where %s=? and %s=?",FairBankno.ID,dao.tableName(),FairBankno.DELETETAG,FairBankno.ID);
        FairBankno no=dao.findFirst(sql,0,bankId);
        if (no==null){
            return false;
        }else{
            return true;
        }
    }

}
